<?php
declare (strict_types = 1);

namespace app;

use app\common\library\Response;
use think\App;
use think\facade\View;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;
        $this->response = new Response();
        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {
        $data['static_url'] = get_host(); //全局的静态数据的访问地址,可切换配置
        $this->assign('PUBCJ', cache_str())//全局的静态文件更新缓存key
        ->assign('conf', $data);
    }

    /*
     * @title 成功返回数据
     * */
    public function success(string $msg,array $data = [])
    {
        if($this->request->isAjax()){
            return $this->response->success($data,$msg)->getResult();
        }
        View::assign('data',$this->response->success($data,$msg)->setType('raw')->getResult());
        return View::fetch('../tpl/dispatch_jump.html');
    }

    /*
     * @title 失败返回数据
     * */
    public function error(string $msg)
    {
        if($this->request->isAjax()){
            return $this->response->error($msg)->getResult();
        }
        View::assign('data',$this->response->error($msg)->setType('raw')->getResult());
        return View::fetch('../tpl/dispatch_jump.html');
    }

    /*
     * @title 模板赋值
     * */
    public function assign($name,$val) :self
    {
        View::assign($name,$val);
        return $this;
    }

    //空方法
    public function __call($method, $args)
    {
        if ($this->request->isAjax()) {
            return $this->response->error('您访问的页面不存在', 404, 404)->getResult();
        } else {
            return view('common@/404');
        }
    }

}

